import axios from "axios";
import { message, loadingBar } from "./naiveUiDiscrete";
import { storage } from "@/utils/Storage";
import { ContentTypeEnum, ResultEnum } from "@/enums/httpEnum";
import storageEnum from "@/enums/storageEnum";

// 存储所有请求的Map
const pendingRequestMap = new Map();

/**
 * 生成请求的唯一key
 * @param {Object} config 请求配置
 * @returns {string} 唯一key
 */
function generateReqKey(config) {
  const { method, url, params, data } = config;
  return [method, url, JSON.stringify(params), JSON.stringify(data)].join("&");
}

/**
 * 添加请求到pendingRequest
 * @param {Object} config 请求配置
 */
function addPendingRequest(config) {
  const requestKey = generateReqKey(config);
  config.cancelToken =
    config.cancelToken ||
    new axios.CancelToken((cancel) => {
      if (!pendingRequestMap.has(requestKey)) {
        pendingRequestMap.set(requestKey, cancel);
      }
    });
}

/**
 * 移除pendingRequest中的请求
 * @param {Object} config 请求配置
 */
function removePendingRequest(config) {
  const requestKey = generateReqKey(config);
  if (pendingRequestMap.has(requestKey)) {
    const cancel = pendingRequestMap.get(requestKey);
    cancel(requestKey);
    pendingRequestMap.delete(requestKey);
  }
}

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 10000,
  headers: {
    "Content-Type": ContentTypeEnum.JSON,
  },
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 移除之前的相同请求
    removePendingRequest(config);
    // 添加当前请求
    addPendingRequest(config);

    // 显示加载条
    loadingBar.start();

    // 添加token
    const token = storage.get(storageEnum.ACCESS_TOKEN);
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    return config;
  },
  (error) => {
    loadingBar.error();
    return Promise.reject(error);
  },
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // 移除请求记录
    removePendingRequest(response.config);
    loadingBar.finish();

    const res = response.data;

    // 根据业务状态码处理
    if (![ResultEnum.SUCCESS200, ResultEnum.SUCCESS0].includes(res.code)) {
      message.error(res.message || "请求失败");
      return Promise.reject(new Error(res.message || "Error"));
    }

    return res;
  },
  (error) => {
    // 移除请求记录
    if (error.config) {
      removePendingRequest(error.config);
    }
    loadingBar.error();

    // 如果是取消的请求，不显示错误
    if (axios.isCancel(error)) {
      console.log("请求已取消:", error.message);
      return Promise.reject(error);
    }

    // 处理HTTP错误
    if (error.response) {
      const status = error.response.status;
      const errorMessage = getErrorMessage(status);
      message.error(errorMessage);

      // 401跳转登录页
      if (status === 401) {
        console.log("跳转到登录页");
        // window.location.href = '/login'
      }
    } else if (error.request) {
      message.error("请求超时，请检查网络连接");
    } else {
      message.error("请求发送失败");
    }

    return Promise.reject(error);
  },
);

/**
 * 获取错误信息
 * @param {number} status HTTP状态码
 * @returns {string} 错误信息
 */
function getErrorMessage(status) {
  const messageMap = {
    400: "请求错误(400)",
    401: "未授权，请登录(401)",
    403: "拒绝访问(403)",
    404: "请求的资源不存在(404)",
    405: "请求方法不允许(405)",
    408: "请求超时(408)",
    500: "服务器错误(500)",
    501: "服务未实现(501)",
    502: "网络错误(502)",
    503: "服务不可用(503)",
    504: "网络超时(504)",
    505: "HTTP版本不受支持(505)",
  };

  return messageMap[status] || `连接出错(${status})`;
}

/**
 * 取消所有pending状态的请求
 */
export function cancelAllPendingRequests() {
  for (const [requestKey, cancel] of pendingRequestMap) {
    cancel(requestKey);
  }
  pendingRequestMap.clear();
}

/**
 * 取消指定的pending请求
 * @param {string|Array} requestKeys 要取消的请求key或key数组
 */
export function cancelPendingRequests(requestKeys) {
  const keys = Array.isArray(requestKeys) ? requestKeys : [requestKeys];
  keys.forEach((key) => {
    if (pendingRequestMap.has(key)) {
      const cancel = pendingRequestMap.get(key);
      cancel(key);
      pendingRequestMap.delete(key);
    }
  });
}

/**
 * GET请求
 * @param {string} url 请求地址
 * @param {Object} params 请求参数
 * @param {Object} config 额外配置
 */
export function get(url, params = {}, config = {}) {
  return service.get(url, { params, ...config });
}

/**
 * POST请求
 * @param {string} url 请求地址
 * @param {Object} data 请求数据
 * @param {Object} config 额外配置
 */
export function post(url, data = {}, config = {}) {
  return service.post(url, data, config);
}

/**
 * PUT请求
 * @param {string} url 请求地址
 * @param {Object} data 请求数据
 * @param {Object} config 额外配置
 */
export function put(url, data = {}, config = {}) {
  return service.put(url, data, config);
}

/**
 * DELETE请求
 * @param {string} url 请求地址
 * @param {Object} params 请求参数
 * @param {Object} config 额外配置
 */
export function del(url, params = {}, config = {}) {
  return service.delete(url, { params, ...config });
}

/**
 * 文件上传
 * @param {string} url 请求地址
 * @param {FormData} formData FormData对象
 * @param {Object} config 额外配置
 */
export function upload(url, formData, config = {}) {
  return service.post(url, formData, {
    headers: {
      "Content-Type": ContentTypeEnum.FORM_DATA,
    },
    ...config,
  });
}

export default {
  service,
  get,
  post,
  put,
  del,
  upload,
  cancelAllPendingRequests,
  cancelPendingRequests,
};
